# -*- coding:utf-8 -*-
import ctypes
import threading
import MySQLdb
import os
import socket
import json
import httplib
import urllib2
import uuid
import zipfile
import base64
import sys
import hashlib
import datetime
import time
import subprocess
import xml.dom.minidom

# m = hashlib.md5(str(425349261)) 
# m.digest()
# md5  = m.hexdigest()
# str1 = md5[0: 2]
# str2 = md5[2: 4]

# random_filename = '/data/app/ipas/'+ str1 + "/" + str2 + "/" + str(md5) + str2 + str1 + '.ipa'
# print random_filename
# sys.exit()

db_host   = "192.168.11.6"
db_user   = 'xyzs'
db_passwd = 'ikF5NNeJg2G8'
db_port   = 3309
db_name   = "app_xyapplist"

def commom_log(filename, content , write_type='wb'):
    try:
        f = open(filename , write_type)
        f.write(content);
        f.close()
    except:
        print('happen an exception when write file')
        return ""

def get_version(random_filename):
    try:
        zf = zipfile.ZipFile(random_filename, "a")
        zf.getinfo("iTunesMetadata.plist")
        data = zf.read("iTunesMetadata.plist")
        if data :

            index   = data.rfind('account hash')
            if index != -1:
                index_right = data.find('</string>', index)
                useraccount = data[index: index_right]
                useraccount = useraccount.replace("account hash</key>" , '').replace("<string>", "").strip()
            else:
                useraccount = ''

            index   = data.rfind('itemId')
            if index != -1:
                index_right = data.find('</integer>', index)
                itunesid = data[index: index_right]
                itunesid = itunesid.replace("itemId</key>" , '').replace("<integer>", "").strip()
            else:
                itunesid = ''

            index   = data.rfind('bundleShortVersionString')
            if index != -1:
                index_right = data.find('</string>', index)
                version = data[index: index_right]
                version = version.replace("bundleShortVersionString</key>" , '').replace("<string>", "").strip()
            else:
                version = ''

            index   = data.rfind('bundleVersion')
            if index != -1:
                index_right = data.find('</string>', index)
                bundleVersion = data[index: index_right]
                bundleVersion = bundleVersion.replace("bundleVersion</key>" , '').replace("<string>", "").strip()
            else:
                bundleVersion = ''

            return  version,bundleVersion,useraccount,itunesid
        else:
            return '','','',''
    except:
        return '','','',''


arr  = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f'
arr  = arr.split(",")
conn = MySQLdb.connect(host=db_host,user=db_user,passwd=db_passwd,port=db_port,init_command="set names utf8")
conn.select_db(db_name)
cur  = conn.cursor()

# is_genuine = 1

# for x in arr:
#     for xx in arr :
#         tb_name = 'app_xyapplist_'+str(x)+".t_xyapplist_"+x+xx
#         sql  = "update "+tb_name+" set is_hot = 0;";
#         print sql + "\n"
#         # cur.execute(sql)

#         sql = 'update ' + tb_name +' a , app_xyapplist.t_xyapplist_hot b set a.is_hot = 1 where a.itunesid = b.itunesid;'
#         print sql + "\n"
        # cur.execute(sql)

# cur.close()
# conn.close()

## =============================================================================================

for x in arr:
    for xx in arr :
        tb_name = 'app_xyapplist_'+str(x)+".t_xyapplist_"+x+xx

        sql  = "select itunesid from "+tb_name+" where is_j_install = 1 and is_hot = 1 and childid not in(13007,13006,13008,13009,13010,13011,13012,13013,13014,13015,13002,13017,13018,13003,13019,13020,13021,13001,13004,13023,13024,13025,13026,13027,13005,13028,13029,13030);";

        cur.execute(sql)
        result = cur.fetchall()
        for f in result:

            itunesid = f[0]

            print itunesid
            m = hashlib.md5(str(itunesid)) 
            m.digest()
            md5  = m.hexdigest()
            str1 = md5[0: 2]
            str2 = md5[2: 4]

            random_filename = '/data/app/jailbreak/'+ str1 + "/" + str2 + "/" + str(itunesid) + '.ipa'

            if os.path.exists(random_filename):
                print random_filename
                download_url = 'http://download.xyzs.com/jailbreak/'+str1+'/'+str2+'/'+str(itunesid)+'.ipa'
                commom_log('download_log.log' , download_url + "\n" , "a")

cur.close()
conn.close()

# for x in arr:
#     for xx in arr :
#         tb_name = 'app_xyapplist_'+str(x)+".t_xyapplist_"+x+xx

#         sql  = "select itunesid from "+tb_name+" where is_install = 1 and is_hot = 0;";

#         cur.execute(sql)
#         result = cur.fetchall()
#         for f in result:

#             itunesid = f[0]

#             print itunesid
#             m = hashlib.md5(str(itunesid)) 
#             m.digest()
#             md5  = m.hexdigest()
#             str1 = md5[0: 2]
#             str2 = md5[2: 4]

#             random_filename = '/data/app/ipas/'+ str1 + "/" + str2 + "/" + str(md5) + str2 + str1 + '.ipa'

#             if os.path.exists(random_filename):
#                 print random_filename
#                 download_url = 'http://download.xyzs.com/ipas/'+str1+'/'+str2+'/'+md5+str2+str1+'.ipa'
#                 commom_log('download_log.log' , download_url + "\n" , "a")

# cur.close()
# conn.close()


# account_hash = set(["35c76380fa673d1dbfcd4d4883ea7a75","f3b84e29fc0cc039d00fa2d04131b2fa","d3522b6522fa66ce45845dd61087301f","75db69255788386afa43ee8308eb0c60","3969c2528bf935bf0e5946be2da9836d","49cc397f570c4f8c2649297d07514022","2092feeb34b415867874ad27dfa195ee"])

# for x in arr:
#     for xx in arr :
#         tb_name = 'app_xyapplist_'+str(x)+".t_xyapplist_"+x+xx

#         sql  = "select itunesid , version , bundleVersion , useraccount from "+tb_name+" where is_install = 1 and is_genuine = 1 ;";

#         cur.execute(sql)
#         result = cur.fetchall()
#         for f in result:

#             itunesid = f[0]
#             db_version = f[1]
#             db_bundleVersion = f[2]
#             db_useraccount   = f[3]

#             print itunesid
#             m = hashlib.md5(str(itunesid)) 
#             m.digest()
#             md5  = m.hexdigest()
#             str1 = md5[0: 2]
#             str2 = md5[2: 4]

#             random_filename = '/data/app/ipas/'+ str1 + "/" + str2 + "/" + str(md5) + str2 + str1 + '.ipa'

#             if os.path.exists(random_filename):
#                 print random_filename
#                 return_value = get_version(random_filename)
#                 if return_value[2] not in account_hash :
#                     # 更新 DB 
#                     commom_log('account_hast_log.log' , str(itunesid) + "----" + db_useraccount + "===" + return_value[2] + "---" + random_filename + "\n" , "a")    
#             else:
#                 # 更新 DB
#                 commom_log('file_not_exit.log' , str(itunesid) + "----" + db_useraccount + "---" + random_filename + "\n" , "a")
# cur.close()
# conn.close()